//
//  SEGiKeyManager.m
//  Uhomebk
//
//  Created by Chiang on 2018/3/2.
//  Copyright © 2018年 mac. All rights reserved.
//

#import "SEGiKeyManager.h"

//static NSString *const iKeyPid = @"0oki87uyhnj76545tgls987"; ///< 招商智锁key
static NSString *const iKeyPid = @"y567erdiyu876yrwe32e0o983k"; ///< 智锁key
static NSTimeInterval const kScanTimeInterval = 0.4;

@interface SEGiKeyManager ()

@property (nonatomic, strong) NPDSophKey *sophKey;

@end

@implementation SEGiKeyManager

+ (instancetype)sharedIkey {
    static SEGiKeyManager *_sharedIkey = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedIkey = [[self alloc] init];
    });
    return _sharedIkey;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        self.sophKey = [NPDSophKey sharedSophKey];
        [self.sophKey configureWithPid:iKeyPid delegate:self];
    }
    return self;
}

#pragma mark - Methods
/**
 * 发起开门操作
 */
- (void)openDoor {
    _key = self.doorModel.ssid;
    _macAddress = self.doorModel.deviceid;
    [self.sophKey startScanWithInterval:kScanTimeInterval serviceUUIDs:@[@"2560",@"FEE7"] immediately:NO];
}

#pragma mark - NPDSophKeyDelegate

//初始化结果
- (void)initResult:(BOOL)success errorCode:(NPDErrorCode)code {
    if (success) {
        
    } else {
        [self seg_opendoorFail];
    }
}

/**
 * 扫描结果
 * success:YES,扫描成功，NO，扫描失败
 * code:扫描失败时，返回具体的错误码
 * infos:如果扫描失败，为nil，如果扫描成功，返回周边扫描到的设备
 **/
- (void)scanResult:(BOOL)success errorCode:(NPDErrorCode)code extInfo:(NSArray *)infos {
    if (success) {
        if (infos && [infos count] > 0) {
            BOOL foundDevice = NO;
            for (NSDictionary *item in infos) {
                if ([self checkIkeyDevice:item]) {
                    foundDevice = YES;
                    return;
                }
            }
            if (!foundDevice) {
                [self seg_opendoorFail];
            }
        } else {
            [self seg_opendoorFail];
        }
    } else {
        [self seg_opendoorFail];
    }
}

/**
 检查是否是ikey设备，如果是则发送开门指令
 @param device 设备信息
 */
- (BOOL)checkIkeyDevice:(NSDictionary *)device {
    if (device && [device[K_TYPE] isEqual:@1] && [device[K_MAC] isEqualToString:_macAddress]) {//1表示是ikey设备
        [self.sophKey openDoorWithKey:_key fwVersion:[device[K_FW_VERSION] shortValue] peripheral:device[K_PERIPHERAL]];
        return YES;
    }
    return NO;
}

/**
 * 开门结果
 * success:YES,开门成功，NO，开门失败
 * code:开门失败时，返回具体的错误码
 * infor:附加信息
 **/
- (void)openDoorResult:(BOOL)success errorCode:(NPDErrorCode)code extInfo:(NSDictionary *)info {
    if (success) {
        if (self.delegateSubject) {
            [self.delegateSubject sendNext:nil];
        }
    } else {
        [self seg_opendoorFail];
    }
}

/**
 蓝牙开门错误提示语
 @param code 错误编码
 */
- (NSString *)errorMessageWithCode:(NPDErrorCode)code {
    NSString *errorMessage = nil;
    switch (code) {
        case NPDBluetoothNotOpen:
            errorMessage = @"请打开蓝牙";
            break;
        case NPDScanNotFoundDevice:
            errorMessage = @"未发现设备";
            break;
        case NPDOpenDoorFailed:
            errorMessage = @"开门失败";
            break;
        case NPDConnectFailed:
            errorMessage = @"设备连接失败";
            break;
        default:
            errorMessage = @"开门失败";
            break;
    }
    return errorMessage;
}

#pragma mark - handle
/// 处理开门失败
- (void)seg_opendoorFail {
    if (self.delegateSubject) {
       NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:SEGOpenDoorErrorType_OpenBluetoothDoorFail userInfo:@{NSLocalizedDescriptionKey:kOpenDoorMessage_Failed}];
       [self.delegateSubject sendError:error];
    }
}

@end
